<template>
  <div>
    <authTable
      ref="authTable"
      v-loading="loading"
      :table-opts="tableOpts"
      :is-show-column="true"
      :is-column-search="false"
      :pagination-data="{
        total: total,
        queryParams: filterForm
      }"
      @pagination="pagination"
      @searchReset="handleReset"
      @searchChange="handleQuery"
      @handleSelectionChange="handleSelectionChange"
    >
      <template #toolbarBtn>
        <el-input
          v-model="filterForm.realName"
          placeholder="请输入用户姓名"
          style="width:280px"
          maxlength="30"
          size="small"
          clearable
          @keyup.enter.native="handleQuery"
          @clear="handleReset"
        />
        <div class="btnGroup">
          <el-button v-permission="['BUSSINESSROLEMANAGE_ADDUSER_BUTTON']" size="small" type="primary"
                     @click="handleAddUSer">添加用户</el-button>
          <el-button v-preventReClick="3000" v-permission="['BUSSINESSROLEMANAGE_DELMORE_BUTTON']" size="small"
                     @click="handleDelete()">批量移除</el-button>
        </div>
      </template>
      <template #realName="row">
        <div class="name-avatar">
          <el-avatar
            size="small"
            class="name-circle"
          >
            <span class="name-text">{{ row.param.realName.substring(row.param.realName.length-1) }}</span>
          </el-avatar>
          <span class="realname">{{ row.param.realName }}</span>
        </div>
      </template>
    </authTable>
    <personSelect ref="personPicker" v-model="personValue" :params="params"
                  :search-user-params="searchUserParams" :tag-visible="false" :selected-data="select"
                  :api="bussinessRoleManageApi" @input="handlePersonInput" @handleSelectData="selected" />
  </div>
</template>
<script>
// import bussinessRoleManage from '@/framework/api/authCenter/bussinessRoleManage'
import { getRoleUserPage, batchDeleteUsers, grantRoleUsers, getManagingOrgUserList, searchOrgName, searchUserName } from '@/framework/api/authCenter/bussinessRoleManage'

export default {
  dicts: [],
  props: {
    roleInfo: {
      type: Object,
      default() {
        return {}
      }
    }
  },
  data() {
    return {
      bussinessRoleManageApi: { getManagingOrgUserList, searchOrgName, searchUserName },
      // 遮罩层
      loading: false,
      // 总条数
      total: 0,
      // 用户组织机构关联表格数据
      list: [],
      // 查询参数
      filterForm: {
        realName: '',
        positionName: '',
        orgName: '',
        roleId: '',
        pageNo: 1,
        pageSize: 10
      },
      tableOpts: {
        rowKey: 'userId',
        tableData: [],
        toolbarBtn: [],
        // 表格第一列
        firstTableCol: {
          select: true,
          width: 55,
          type: 'selection'
        },
        tableCol: [
          {
            prop: 'account',
            label: '账号',
            show: true,
            search: true
          },
          {
            prop: 'realName',
            label: '姓名',
            show: true,
            search: true
            // slotName: 'realName'
          },
          {
            prop: 'positionName',
            label: '岗位',
            show: true,
            columnSearch: false
          },
          {
            prop: 'orgName',
            label: '所属组织',
            show: true,
            columnSearch: false
          }
        ],
        operator: {
          operatorBtn: [
            {
              text: '移除',
              permission: ['BUSSINESSROLEMANAGE_DELUSER_BUTTON'],
              size: 'small',
              type: 'danger',
              click: (row, col, cellValue) => { return this.handleDelete(row) }
            }
          ]
        }
      },
      multipleSelection: [],
      personValue: '',
      select: [],
      params: {
        roleId: ''
      },
      searchUserParams: {
        roleId: ''
      }
    }
  },
  watch: {
    roleInfo(newValue, oldValue) {
      if (newValue) {
        this.params.roleId = newValue.roleId
        this.searchUserParams.roleId = newValue.roleId
        this.getList(newValue.roleId)
      }
    },
    'filterForm.realName': function (newValue) {
      this.filterForm.realName = newValue
      this.getList(this.roleInfo.roleId)
    }
  },
  created() {
    if (this.roleInfo.roleId) {
      this.params.roleId = this.roleInfo.roleId
      this.searchUserParams.roleId = this.roleInfo.roleId
      this.getList(this.roleInfo.roleId)
    }
  },
  methods: {
    getList(roleId) {
      this.loading = true
      this.filterForm.roleId = roleId
      this.$nextTick(() => {
        this.$refs.authTable.clearSelection()
      })
      getRoleUserPage(this.filterForm).then((res) => {
        this.tableOpts.tableData = res.data.rows
        this.total = res.data.totalRows
        this.loading = false
      })
    },
    /** 搜索按钮操作 */
    handleQuery(formModel) {
      this.filterForm = { ...this.filterForm, ...formModel }
      this.filterForm.pageNo = 1
      this.getList(this.roleInfo.roleId)
    },
    /** 重置按钮操作 */
    handleReset() {
      this.filterForm = {
        realName: '',
        positionName: '',
        orgName: '',
        roleId: '',
        pageNo: 1,
        pageSize: 10
      }
      this.handleQuery()
    },
    // 查询列表
    pagination() {
      this.getList(this.roleInfo.roleId)
    },
    // 多选框选中数据
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    handleDelete(row) {
      let userIds = []
      if (this.multipleSelection.length === 0 && !row) {
        this.$dtMessage({
          type: 'error',
          message: '请至少选中一条数据'
        })
        return false
      }
      if (row) {
        userIds = row.userId
      } else {
        userIds = this.multipleSelection.map((res) => {
          return res.userId
        }).join(',')
      }
      this.$dtMessageBox({ title: '提示', message: this.multipleSelection.length > 0 ? '是否确认批量移除?' : `是否确认移除“${row.realName}”?`, type: 'warning' }).then(() => {
        batchDeleteUsers({ userIds, roleId: this.roleInfo.roleId }).then((res) => {
          this.getList(this.roleInfo.roleId)
          userIds = []
          this.$dtMessage({
            message: '删除成功',
            type: 'success'
          })
        })
      }).catch(() => {
        // 取消不做操作
      })
    },
    handleAddUSer() {
      this.$refs.personPicker.show()
    },
    handlePersonInput() {
      grantRoleUsers({ roleId: this.roleInfo.roleId, userIds: this.personValue }).then((res) => {
        this.$dtMessage({
          message: '新增成功',
          type: 'success'
        })
        this.select = []
        this.getList(this.roleInfo.roleId)
      })
    },
    selected(select) {
      this.select = select
    }
  }
}
</script>
<style scoped lang="scss">
.btnGroup {
  flex: 1;
  margin-right: 16px;

  button {
    margin-bottom: 0 !important;
    margin-left: 16px;
    float: right;
  }
}
</style>
